Skip to content

✨ Join table with category#148

Open
anchovy1st wants to merge 2 commits intomainfrom
feat/147-apply-join-with-category-table
Open

✨ Join table with category#148
anchovy1st wants to merge 2 commits intomainfrom
feat/147-apply-join-with-category-table

Conversation

@anchovy1st
Copy link
Contributor

@anchovy1st anchovy1st commented Jun 3, 2025

📌 관련 이슈

Summary by CodeRabbit

  • 신규 기능

    • 댓글에 카테고리 정보(슬러그, 라벨, 이모지)가 함께 제공됩니다.
    • 댓글 목록 조회 시, 각 댓글의 카테고리 정보가 함께 표시됩니다.
  • 버그 수정

    • 카테고리가 없는 댓글도 정상적으로 조회됩니다.

@anchovy1st anchovy1st self-assigned this Jun 3, 2025
@anchovy1st anchovy1st added enhancement New feature or request feat implement function be Backend labels Jun 3, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 3, 2025

"""

Walkthrough

댓글과 관련된 카테고리 정보를 함께 처리하도록 DTO, 레포지토리, 서비스 구현이 확장되었습니다. 댓글 응답 DTO에 카테고리 필드가 추가되고, 댓글과 카테고리 정보를 함께 조회 및 반환하는 로직이 도입되었습니다. JPQL LEFT JOIN 쿼리와 관련 메서드가 추가되었습니다.

Changes

파일/경로 변경 요약
src/main/java/com/handongapp/cms/dto/v1/CommentDto.java 댓글 응답 DTO에 카테고리 관련 필드(categorySlug, categoryLabel, categoryEmoji) 추가, 생성자 및 팩토리 메서드 오버로딩
src/main/java/com/handongapp/cms/repository/CommentRepository.java 댓글과 카테고리 정보를 LEFT JOIN으로 함께 조회하는 JPQL 메서드 추가
src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java 카테고리 레포지토리 주입, 댓글 생성/수정/검색 시 카테고리 정보 포함하여 DTO 반환 로직 추가

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CommentServiceImpl
    participant CommentRepository
    participant CommentOfCategoryRepository

    Client->>CommentServiceImpl: searchComments(조건)
    CommentServiceImpl->>CommentRepository: findCommentsWithCategoriesByCriteria(조건)
    CommentRepository-->>CommentServiceImpl: List<Object[]> (TbComment, TbCommentOfCategory)
    loop 각 결과에 대해
        CommentServiceImpl->>CommentDto.Response: from(TbComment, TbCommentOfCategory)
    end
    CommentServiceImpl-->>Client: List<CommentDto.Response>
Loading

Poem

🥕
댓글에 카테고리 꽃이 피었네,
레포지토리에서 JOIN하며 춤추네.
DTO에 이모지까지 담아,
서비스는 풍성하게 응답하네.
토끼는 기뻐서 깡총깡총,
코드에도 봄바람이 솔솔!

"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1779fd4 and 3a28329.

📒 Files selected for processing (1)
  • src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (4)
src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java (4)

40-47: 성능 최적화를 위해 JOIN 쿼리 사용을 고려해보세요.

현재 구현은 댓글 저장 후 별도의 쿼리로 카테고리를 조회하고 있습니다. 이는 추가적인 데이터베이스 호출을 발생시킵니다.

더 일관되고 효율적인 방법으로 개선할 수 있습니다:

-// 카테고리 정보를 함께 반환하기 위해 카테고리 조회
-TbCommentOfCategory category = null;
-if (savedComment.getCategoryId() != null) {
-    category = commentOfCategoryRepository.findById(savedComment.getCategoryId()).orElse(null);
-}
-
-return CommentDto.Response.from(savedComment, category);
+// JOIN 쿼리를 사용하여 댓글과 카테고리를 함께 조회
+List<Object[]> result = commentRepository.findCommentsWithCategoriesByCriteria(
+        null, null, DELETED_STATUS_NO);
+Object[] commentWithCategory = result.stream()
+        .filter(r -> ((TbComment) r[0]).getId().equals(savedComment.getId()))
+        .findFirst()
+        .orElse(new Object[]{savedComment, null});
+
+TbComment comment = (TbComment) commentWithCategory[0];
+TbCommentOfCategory category = commentWithCategory.length > 1 ? 
+        (TbCommentOfCategory) commentWithCategory[1] : null;
+
+return CommentDto.Response.from(comment, category);

61-68: create 메소드와 동일한 성능 최적화 적용 필요

update 메소드도 create 메소드와 동일한 성능 이슈가 있습니다. 별도의 카테고리 조회 대신 JOIN 쿼리를 사용하는 것을 고려해보세요.


40-47: 성능 최적화를 고려해보세요.

현재 댓글 저장 후 별도의 데이터베이스 호출로 카테고리를 조회하고 있습니다. 이는 불필요한 추가 쿼리를 발생시킵니다.

다음과 같이 개선할 수 있습니다:

- // 카테고리 정보를 함께 반환하기 위해 카테고리 조회
- TbCommentOfCategory category = null;
- if (savedComment.getCategoryId() != null) {
-     category = commentOfCategoryRepository.findById(savedComment.getCategoryId()).orElse(null);
- }
- 
- return CommentDto.Response.from(savedComment, category);
+ // 카테고리 ID가 있는 경우에만 카테고리 정보와 함께 조회하는 별도 메서드 사용 고려
+ // 또는 요청 시점에 이미 유효한 카테고리인지 검증하여 불필요한 조회 최소화
+ TbCommentOfCategory category = savedComment.getCategoryId() != null ? 
+     commentOfCategoryRepository.findById(savedComment.getCategoryId()).orElse(null) : null;
+ 
+ return CommentDto.Response.from(savedComment, category);

61-68: create 메서드와 동일한 성능 이슈가 있습니다.

update 메서드에서도 별도의 데이터베이스 호출로 카테고리를 조회하고 있어 동일한 성능 최적화가 필요합니다.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9aa133b and 1779fd4.

📒 Files selected for processing (3)
  • src/main/java/com/handongapp/cms/dto/v1/CommentDto.java (3 hunks)
  • src/main/java/com/handongapp/cms/repository/CommentRepository.java (1 hunks)
  • src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java (1)
src/main/java/com/handongapp/cms/dto/v1/CommentDto.java (1)
  • CommentDto (11-129)
🔇 Additional comments (10)
src/main/java/com/handongapp/cms/repository/CommentRepository.java (2)

30-44: 새로운 JOIN 쿼리 메소드 구현이 적절합니다.

LEFT JOIN을 사용하여 카테고리가 없는 댓글도 조회할 수 있도록 한 설계가 올바릅니다. 쿼리 구조와 매개변수 처리도 기존 메소드와 일관성 있게 구현되었습니다.


30-44: JPQL LEFT JOIN 쿼리가 올바르게 구현되었습니다.

LEFT JOIN을 사용하여 카테고리가 없는 댓글도 포함하도록 한 설계가 적절하며, 매개변수 바인딩과 정렬 조건도 정확합니다.

src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java (3)

4-4: 의존성 주입이 올바르게 추가되었습니다.

CommentOfCategoryRepository 의존성 주입과 import 구문이 적절하게 추가되었습니다.

Also applies to: 7-7, 29-29


106-116: JOIN 쿼리를 활용한 효율적인 구현

findCommentsWithCategoriesByCriteria 메소드를 사용하여 한 번의 쿼리로 댓글과 카테고리 정보를 모두 가져오는 구현이 효율적입니다. Object[] 배열 처리 로직도 적절합니다.


4-4: 카테고리 저장소 의존성이 올바르게 추가되었습니다.

새로운 기능을 위한 CommentOfCategoryRepository 의존성 주입이 적절하게 구현되었습니다.

Also applies to: 7-7, 29-29

src/main/java/com/handongapp/cms/dto/v1/CommentDto.java (5)

4-4: DTO 구조 확장이 적절하게 구현되었습니다.

새로운 카테고리 필드들이 final로 선언되어 불변성을 보장하고, 생성자도 올바르게 업데이트되었습니다. import 문도 적절히 추가되었습니다.

Also applies to: 27-29, 32-32, 40-42


45-82: 팩토리 메소드 설계가 우수합니다.

기존 from(TbComment) 메소드를 유지하여 하위 호환성을 보장하면서, 새로운 from(TbComment, TbCommentOfCategory) 메소드를 추가하여 유연성을 제공하는 설계가 훌륭합니다. null 체크도 적절하게 처리되었습니다.


4-4: 카테고리 필드가 적절하게 추가되었습니다.

새로운 카테고리 관련 필드들이 불변 필드로 올바르게 추가되고 생성자도 적절히 업데이트되었습니다.

Also applies to: 27-29, 40-42


32-32: 기존 팩토리 메서드의 하위 호환성이 유지되었습니다.

기존 from(TbComment) 메서드에서 새로운 카테고리 필드들을 null로 초기화하여 기존 코드와의 호환성을 적절히 유지했습니다.

Also applies to: 57-61


64-81: 새로운 팩토리 메서드가 올바르게 구현되었습니다.

null 체크와 삼항 연산자를 사용하여 카테고리 정보가 있을 때만 해당 필드를 설정하도록 안전하게 구현되었습니다.

Comment on lines +42 to +45
TbCommentOfCategory category = null;
if (savedComment.getCategoryId() != null) {
category = commentOfCategoryRepository.findById(savedComment.getCategoryId()).orElse(null);
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jun 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

카테고리 존재성 검증 추가를 고려해보세요.

현재 구현은 categoryId가 존재하지만 해당 카테고리가 데이터베이스에 없는 경우를 처리하지만, 사용자에게 명확한 피드백을 제공하지 않습니다.

카테고리가 필수인 경우 검증 로직을 추가할 수 있습니다:

// 카테고리 정보를 함께 반환하기 위해 카테고리 조회
TbCommentOfCategory category = null;
if (savedComment.getCategoryId() != null) {
-    category = commentOfCategoryRepository.findById(savedComment.getCategoryId()).orElse(null);
+    category = commentOfCategoryRepository.findById(savedComment.getCategoryId())
+            .orElseThrow(() -> new NotFoundException("지정된 카테고리를 찾을 수 없습니다. ID: " + savedComment.getCategoryId()));
}

Also applies to: 63-66

🤖 Prompt for AI Agents
In src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java around
lines 42 to 45 and similarly at lines 63 to 66, the code fetches a category by
ID but does not handle the case where the category ID exists but the category is
not found in the database. Add validation to check if the category is null after
fetching; if the category is mandatory, throw an appropriate exception or return
a clear error message to inform the user that the category does not exist.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

반영해주세요

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Callein, 카테고리 존재성 검증을 추가하는 코드 변경을 계획하겠습니다.

graph TB
  A["Task: 카테고리 존재성 검증 추가"]
  A --> B["create 메서드의 카테고리 조회 로직 수정"]
  A --> C["update 메서드의 카테고리 조회 로직 수정"]
  B --> D["orElse(null)을 orElseThrow()로 변경"]
  C --> E["orElse(null)을 orElseThrow()로 변경"]
  D --> F["NotFoundException으로 명확한 에러 메시지 제공"]
  E --> G["NotFoundException으로 명확한 에러 메시지 제공"]
Loading

다른 에이전트가 이 변경사항들을 실제로 구현할 예정입니다. 이 변경으로 카테고리 ID가 존재하지만 해당 카테고리가 데이터베이스에 없는 경우 명확한 에러 메시지와 함께 예외가 발생하게 됩니다.


⏳ Preparing changes...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A summary of the edits CodeRabbit can apply:

CommentServiceImpl.java의 create 및 update 메서드에 카테고리 존재성 검증 로직이 추가될 예정입니다.

A plan of each step that CodeRabbit will take in order to execute the edits for each file (with inline rough draft snippets):

✏️ src/main/java/com/handongapp/cms/service/impl/CommentServiceImpl.java

create 메서드 내부에서 카테고리 조회 부분을 찾습니다 (대략 42~45행):
TbCommentOfCategory category = null; if (savedComment.getCategoryId() != null) { category = commentOfCategoryRepository.findById(savedComment.getCategoryId()).orElse(null); }


위 코드에서 orElse(null) 호출을 다음과 같이 교체합니다. NotFoundException을 던져서 존재하지 않는 카테고리에 대한 명확한 오류 메시지를 제공하도록 합니다:
diff - category = commentOfCategoryRepository.findById(savedComment.getCategoryId()).orElse(null); + category = commentOfCategoryRepository.findById(savedComment.getCategoryId()) + .orElseThrow(() -> new NotFoundException("지정된 카테고리를 찾을 수 없습니다. ID: " + savedComment.getCategoryId()));


update 메서드 내부에서 카테고리 조회 부분을 찾습니다 (대략 63~66행):
TbCommentOfCategory category = null; if (entity.getCategoryId() != null) { category = commentOfCategoryRepository.findById(entity.getCategoryId()).orElse(null); }


위 코드에서 orElse(null) 호출을 다음과 같이 교체합니다. NotFoundException을 던져서 존재하지 않는 카테고리에 대한 명확한 오류 메시지를 제공하도록 합니다:
diff - category = commentOfCategoryRepository.findById(entity.getCategoryId()).orElse(null); + category = commentOfCategoryRepository.findById(entity.getCategoryId()) + .orElseThrow(() -> new NotFoundException("지정된 카테고리를 찾을 수 없습니다. ID: " + entity.getCategoryId()));


파일 상단에 NotFoundException import가 있는지 확인합니다.
java import com.handongapp.cms.exception.data.NotFoundException;
누락되어 있다면 추가합니다.


단위 테스트나 통합 테스트를 실행하여, categoryId가 존재하지 않을 때 NotFoundException이 발생하며 메시지가 올바른지 검증합니다.

  • ✅ Create PR with these edits
  • 📌 Create commit in current branch
  • 📋 Get copyable edits

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Callein 이거 데이터 중에서 댓글은 있는데 댓글 카테고리에 해당하는 카테고리가 없는 댓글이 혹시나 생기는 경우에 해당 댓글을 정상적으로 보전하기 위해 일부로 left join을 사용하면서 null이 가능하도록 해둔 겁니다. 예를 들어 동아리 관리자가 카테고리 정보를 임의로 삭제하였을 때 해당 카테고리에 속한 댓글들을 데이터를 정상적으로 표기하기 위해 있습니다.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@junglesub 이거 케이스 어떻게 할지 봐주세요

Comment on lines +42 to +45
TbCommentOfCategory category = null;
if (savedComment.getCategoryId() != null) {
category = commentOfCategoryRepository.findById(savedComment.getCategoryId()).orElse(null);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

반영해주세요

@github-project-automation github-project-automation bot moved this to Backlog in HANDONG-CMS Jun 5, 2025
@junglesub junglesub requested a review from Callein June 5, 2025 11:32
@Callein Callein moved this from Backlog to In review in HANDONG-CMS Jun 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

be Backend enhancement New feature or request feat implement function

Projects

Status: In review

Development

Successfully merging this pull request may close these issues.

2 participants